import dayjs from 'dayjs'
import { useMusicStore } from "../store/index.js"

const MusicStore = useMusicStore()


//传入初始歌词文本text
export const formatLyric = (text) => {
  if (text === '' || text === undefined) {
    text = "[00:00.000] 作词 : 黄家驹\n[00:01.000] 作曲 : 黄家驹\n[00:02.000]"
  }
  let MusicLyricList = []
  const sortRule = (a, b) => { //设置一下排序规则
    return a.time - b.time;
  }
  let arr = text.split("\n"); //原歌词文本已经换好行了方便很多，我们直接通过换行符“\n”进行切割
  let row = arr.length; //获取歌词行数
  for (let i = 0; i < row; i++) {
    let temp_row = arr[i]; //现在每一行格式大概就是这样"[00:04.302][02:10.00]hello world";
    let temp_arr = temp_row.split("]");//我们可以通过“]”对时间和文本进行分离
    let text = temp_arr.pop(); //把歌词文本从数组中剔除出来，获取到歌词文本了！
    //再对剩下的歌词时间进行处理
    temp_arr.forEach(element => {
      let obj = {};
      let time_arr = element.substr(1, element.length - 1).split(":");//先把多余的“[”去掉，再分离出分、秒
      let s = parseInt(time_arr[0]) * 60 + Math.ceil(time_arr[1]); //把时间转换成与currentTime相同的类型，方便待会实现滚动效果
      obj.time = s;
      obj.text = text;
      MusicLyricList.push(obj); //每一行歌词对象存到组件的lyric歌词属性里
    });
  }
  MusicLyricList.sort(sortRule);//由于不同时间的相同歌词我们给排到一起了，所以这里要以时间顺序重新排列一下
  MusicStore.changeLyric(MusicLyricList)
  //把歌词提交到store里，为了重新进入该组件时还能再次渲染
}


//根据时间戳 返回分秒
export const TimeForMate = (timestamp) => {
  return dayjs(timestamp).format("mm:ss")
}

//根据时间返回秒数
export const TimeToSecond = (s) => {
  if (s === '' || s === undefined) {
    s = '00:00'
  }

  let NewArr = s.split(":")
  let second = 0
  second = Number(NewArr[0]) * 60 + Number(NewArr[1])
  return second
}
// 秒转换时分钟00:00:00时分秒格式
export const timeToMinute = (times) => {
  if (times === '' || times === undefined) {
    s = 0
  }
  let t;
  if (times > -1) {
    let min = Math.floor(times / 60) % 60;
    let sec = times % 60;
    if (min < 10) {
      t = '0' + min + ":";
    } else {
      t = min + ":";
    }
    if (sec < 10) {
      t += "0";
    }
    t += sec.toFixed(2);
  }
  t = t.substring(0, t.length - 3);

  return t;
}



